package com.leetcode.binarytree;

import java.util.Deque;
import java.util.LinkedList;

/**
 * date:
 * description:
 */
public class MaxWidth {
    public int widthOfBinaryTree(TreeNode root) {
        if(root == null){
            return 0;
        }
        Deque<TreeNode> nodeQueue = new LinkedList<>();
        Deque<Integer> indexQueue = new LinkedList<>();
        nodeQueue.offer(root);
        indexQueue.offer(1);
        int res = 1;
        while(!nodeQueue.isEmpty()){
            for(int i = nodeQueue.size(); i > 0; i--){
                TreeNode node = nodeQueue.poll();
                int index = indexQueue.poll();
                if(node.left != null){
                    nodeQueue.offer(node.left);
                    indexQueue.offer(2 * index);
                }
                if(node.right != null){
                    nodeQueue.offer(node.right);
                    indexQueue.offer(2 * index + 1);
                }
            }
            if(indexQueue.size() > 1){
                res = Math.max(res, indexQueue.getLast() - indexQueue.getFirst() + 1);
            }
        }
        return res;

    }
}
